package com.xuecheng.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.auth.feignclient.checkcode.CheckCodeClient;
import com.xuecheng.auth.mapper.XcMenuMapper;
import com.xuecheng.auth.mapper.XcUserMapper;
import com.xuecheng.auth.model.dto.AuthParamsDto;
import com.xuecheng.auth.model.dto.XcUserExt;
import com.xuecheng.auth.model.po.XcMenu;
import com.xuecheng.auth.model.po.XcUser;
import com.xuecheng.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    XcUserMapper xcUserMapper;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    XcMenuMapper xcMenuMapper;

    /**
     * 查询用户信息组成用户身份信息
     * @param s 账号
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        try{
            //将认证参数转换为AuthParamsDto类型
            authParamsDto = JSON.parseObject(s,AuthParamsDto.class);
        }catch(Exception e){
            log.error("认证请求不符合项目要求:{}",s);
            throw new RuntimeException("认证请求数据格式不对");
        }
        String authType = authParamsDto.getAuthType();
        AuthService authService = applicationContext.getBean(authType +
                "_authservice",AuthService.class);
        XcUserExt user = authService.execute(authParamsDto);
        return getUserPincipal(user);
    }

    /**
     * 获取用户信息
     * @param xcUser
     * @return
     */
    private UserDetails getUserPincipal(XcUserExt xcUser) {
        //取出数据库存储的正确的密码
        String password = xcUser.getPassword();
        //然后查询用户权限
        List<XcMenu> menus = xcMenuMapper.selectPermissionByUserId(xcUser.getId());
        //用户权限，如果不加，则报Cannot pass a null GrantedAuthority collection
        List<String> authoritieList = menus.stream()
                .map(XcMenu::getCode).collect(Collectors.toList());
        if(authoritieList.isEmpty()){
            authoritieList.add("p1");
        }
        xcUser.setPermissions(authoritieList);
        String[] authorities = authoritieList.toArray(new String[0]);
        //为了安全，在令牌中不放密码
        xcUser.setPassword(null);
        //将user对象转为json存入userDetails中
        String userString = JSON.toJSONString(xcUser);
        //创建UserDetails对象
        UserDetails userDetails = User.withUsername(userString)
                .password(password).authorities(authorities).build();
        return userDetails;
    }
}
